import React, { useState } from 'react';
import {
  Card,
  Typography,
  Form,
  Input,
  Button,
  Space,
  Divider,
  Avatar,
  Alert,
  Descriptions,
  Modal,
  message
} from 'antd';
import {
  UserOutlined,
  MailOutlined,
  EditOutlined,
  SaveOutlined,
  LockOutlined,
  SafetyOutlined,
  CopyOutlined,
  CrownOutlined
} from '@ant-design/icons';

import { useAuth } from '../contexts/AuthContext';
import { useWallet } from '../contexts/WalletContext';
import { useQuery, useMutation, useQueryClient } from 'react-query';

const { Title, Text } = Typography;

const Profile = () => {
  const [form] = Form.useForm();
  const [isEditing, setIsEditing] = useState(false);
  const [changePasswordModalVisible, setChangePasswordModalVisible] = useState(false);
  const [passwordForm] = Form.useForm();

  const { user, updateProfile } = useAuth();
  const { account } = useWallet();
  const queryClient = useQueryClient();

  // Fetch user profile data
  const { data: profileData, isLoading } = useQuery(
    'userProfile',
    () => {
      // Use the user data from auth context
      return Promise.resolve(user);
    },
    { enabled: !!user }
  );

  const updateProfileMutation = useMutation(
    (data) => updateProfile(data),
    {
      onSuccess: () => {
        message.success('Profile updated successfully!');
        setIsEditing(false);
        queryClient.invalidateQueries('userProfile');
      },
      onError: (error) => {
        message.error(error.response?.data?.error || 'Failed to update profile');
      }
    }
  );

  const handleUpdateProfile = async (values) => {
    updateProfileMutation.mutate(values);
  };

  const handleEdit = () => {
    form.setFieldsValue({
      email: profileData?.email || ''
    });
    setIsEditing(true);
  };

  const handleCancel = () => {
    setIsEditing(false);
    form.resetFields();
  };

  const copyToClipboard = (text, type) => {
    navigator.clipboard.writeText(text);
    message.success(`${type} copied to clipboard!`);
  };

  const formatAddress = (address) => {
    if (!address) return '';
    return `${address.slice(0, 6)}...${address.slice(-4)}`;
  };

  const formatDate = (dateString) => {
    return new Date(dateString).toLocaleDateString('en-US', {
      year: 'numeric',
      month: 'long',
      day: 'numeric'
    });
  };

  return (
    <div className="p-6 bg-gray-50 min-h-screen">
      <div className="max-w-4xl mx-auto">
        {/* Header */}
        <div className="mb-8">
          <Title level={2} className="text-gray-900 mb-2">Profile</Title>
          <Text className="text-gray-600">Manage your account settings and information</Text>
        </div>

        <div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
          {/* Profile Card */}
          <div className="lg:col-span-1">
            <Card className="text-center">
              <Avatar
                size={80}
                icon={<UserOutlined />}
                className="bg-blue-600 mb-4"
              />
              <Title level={4} className="mb-2">
                {formatAddress(profileData?.wallet_address)}
              </Title>
              <Text type="secondary" className="block mb-4">
                Member since {formatDate(profileData?.created_at)}
              </Text>

              <div className="space-y-2">
                <div className="bg-gray-50 p-3 rounded-lg">
                  <Text type="secondary" className="text-xs block">Wallet Address</Text>
                  <Text code className="text-sm">{formatAddress(profileData?.wallet_address)}</Text>
                  <Button
                    type="text"
                    size="small"
                    icon={<CopyOutlined />}
                    onClick={() => copyToClipboard(profileData?.wallet_address, 'Wallet address')}
                    className="ml-2"
                  />
                </div>

                <div className="bg-gray-50 p-3 rounded-lg">
                  <Text type="secondary" className="text-xs block">Referral Code</Text>
                  <Text code className="text-sm">{profileData?.referral_code}</Text>
                  <Button
                    type="text"
                    size="small"
                    icon={<CopyOutlined />}
                    onClick={() => copyToClipboard(profileData?.referral_code, 'Referral code')}
                    className="ml-2"
                  />
                </div>

                {profileData?.referred_by && (
                  <div className="bg-blue-50 p-3 rounded-lg">
                    <Text type="secondary" className="text-xs block">Referred By</Text>
                    <Text code className="text-sm">{profileData?.referred_by}</Text>
                  </div>
                )}
              </div>

              <div className="mt-6 pt-6 border-t">
                <div className="flex items-center justify-center space-x-2">
                  <CrownOutlined className="text-yellow-500" />
                  <Text strong>God Token Member</Text>
                </div>
              </div>
            </Card>
          </div>

          {/* Account Information */}
          <div className="lg:col-span-2 space-y-6">
            {/* Personal Information */}
            <Card
              title="Personal Information"
              extra={
                !isEditing && (
                  <Button
                    type="primary"
                    icon={<EditOutlined />}
                    onClick={handleEdit}
                  >
                    Edit
                  </Button>
                )
              }
            >
              {isEditing ? (
                <Form
                  form={form}
                  layout="vertical"
                  onFinish={handleUpdateProfile}
                >
                  <Form.Item
                    label="Email Address"
                    name="email"
                    rules={[
                      { type: 'email', message: 'Please enter a valid email' }
                    ]}
                  >
                    <Input
                      prefix={<MailOutlined />}
                      placeholder="Enter your email"
                    />
                  </Form.Item>

                  <Form.Item>
                    <Space>
                      <Button
                        type="primary"
                        htmlType="submit"
                        icon={<SaveOutlined />}
                        loading={updateProfileMutation.isLoading}
                      >
                        Save Changes
                      </Button>
                      <Button onClick={handleCancel}>
                        Cancel
                      </Button>
                    </Space>
                  </Form.Item>
                </Form>
              ) : (
                <Descriptions column={1}>
                  <Descriptions.Item label="Email Address">
                    {profileData?.email || 'Not provided'}
                  </Descriptions.Item>
                  <Descriptions.Item label="Account Status">
                    <span className="text-green-600">● Active</span>
                  </Descriptions.Item>
                  <Descriptions.Item label="Member Since">
                    {formatDate(profileData?.created_at)}
                  </Descriptions.Item>
                </Descriptions>
              )}
            </Card>

            {/* Security Settings */}
            <Card
              title="Security Settings"
              extra={
                <Button
                  icon={<LockOutlined />}
                  onClick={() => setChangePasswordModalVisible(true)}
                >
                  Change Password
                </Button>
              }
            >
              <div className="space-y-4">
                <div className="flex items-center justify-between p-4 bg-gray-50 rounded-lg">
                  <div className="flex items-center space-x-3">
                    <SafetyOutlined className="text-green-600 text-xl" />
                    <div>
                      <Text strong>Two-Factor Authentication</Text>
                      <div>
                        <Text type="secondary" className="text-sm">
                          Add an extra layer of security to your account
                        </Text>
                      </div>
                    </div>
                  </div>
                  <Button>Enable</Button>
                </div>

                <Alert
                  message="Security Tips"
                  description={
                    <div>
                      <p>• Never share your password with anyone</p>
                      <p>• Use a strong, unique password</p>
                      <p>• Always verify you're on the official website</p>
                      <p>• Keep your wallet secure and never share your private keys</p>
                    </div>
                  }
                  type="info"
                  showIcon
                />
              </div>
            </Card>

            {/* Account Preferences */}
            <Card title="Account Preferences">
              <div className="space-y-4">
                <div className="flex items-center justify-between">
                  <div>
                    <Text strong>Email Notifications</Text>
                    <div>
                      <Text type="secondary" className="text-sm">
                        Receive updates about your staking rewards and account activity
                      </Text>
                    </div>
                  </div>
                  <Button>Configure</Button>
                </div>

                <div className="flex items-center justify-between">
                  <div>
                    <Text strong>Language</Text>
                    <div>
                      <Text type="secondary" className="text-sm">
                        Choose your preferred language
                      </Text>
                    </div>
                  </div>
                  <Button>English</Button>
                </div>

                <div className="flex items-center justify-between">
                  <div>
                    <Text strong>Currency Display</Text>
                    <div>
                      <Text type="secondary" className="text-sm">
                        Choose how to display token amounts
                      </Text>
                    </div>
                  </div>
                  <Button>GOD</Button>
                </div>
              </div>
            </Card>
          </div>
        </div>

        {/* Change Password Modal */}
        <Modal
          title="Change Password"
          open={changePasswordModalVisible}
          onCancel={() => {
            setChangePasswordModalVisible(false);
            passwordForm.resetFields();
          }}
          footer={null}
        >
          <Form
            form={passwordForm}
            layout="vertical"
            onFinish={(values) => {
              // Handle password change
              message.success('Password changed successfully!');
              setChangePasswordModalVisible(false);
              passwordForm.resetFields();
            }}
          >
            <Form.Item
              label="Current Password"
              name="currentPassword"
              rules={[{ required: true, message: 'Please enter your current password' }]}
            >
              <Input.Password
                prefix={<LockOutlined />}
                placeholder="Enter current password"
              />
            </Form.Item>

            <Form.Item
              label="New Password"
              name="newPassword"
              rules={[
                { required: true, message: 'Please enter a new password' },
                { min: 8, message: 'Password must be at least 8 characters' }
              ]}
            >
              <Input.Password
                prefix={<LockOutlined />}
                placeholder="Enter new password"
              />
            </Form.Item>

            <Form.Item
              label="Confirm New Password"
              name="confirmPassword"
              dependencies={['newPassword']}
              rules={[
                { required: true, message: 'Please confirm your new password' },
                ({ getFieldValue }) => ({
                  validator(_, value) {
                    if (!value || getFieldValue('newPassword') === value) {
                      return Promise.resolve();
                    }
                    return Promise.reject(new Error('Passwords do not match'));
                  },
                }),
              ]}
            >
              <Input.Password
                prefix={<LockOutlined />}
                placeholder="Confirm new password"
              />
            </Form.Item>

            <Form.Item>
              <Space className="w-full justify-end">
                <Button onClick={() => setChangePasswordModalVisible(false)}>
                  Cancel
                </Button>
                <Button type="primary" htmlType="submit">
                  Change Password
                </Button>
              </Space>
            </Form.Item>
          </Form>
        </Modal>
      </div>
    </div>
  );
};

export default Profile;